package com.jphotomanager.io;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifIFD0Directory;

public class RawConverter {
    private static final Logger LOGGER = Logger.getLogger(RawConverter.class);
    private String DCRAW_PATH = "/home/nitishkumar/Downloads/dcraw";

    public static boolean isRawFileSupported() {
        return false;
    }

    public static boolean isSupportedRawFile(File file) {
        if (file.getName().toLowerCase().endsWith("cr2"))
            return true;
        else
            return false;
    }

    public static File extractJpeg(File rawFile) {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(rawFile);
            ExifIFD0Directory directory = metadata
                    .getDirectory(ExifIFD0Directory.class);
            String tagName = directory.getString(ExifIFD0Directory.TAG_MAKE);
            if (tagName.toLowerCase().equals("canon")) {
                int stripOffsets = directory.getInt(0x0111);
                int stripByteCounts = directory.getInt(0x0117);
                byte[] readFileToByteArray = FileUtils
                        .readFileToByteArray(rawFile);
                byte[] preview = new byte[stripByteCounts];
                System.arraycopy(readFileToByteArray, stripOffsets, preview, 0,
                        stripByteCounts);
                File jpegFile = getJpegFileNameForRawFile(rawFile);
                FileUtils.writeByteArrayToFile(jpegFile, preview);
                return jpegFile;
            } else if (tagName.toLowerCase().equals("nikon corporation")) {
                
            }
        } catch (Exception e) {
            LOGGER.error("error", e);
        }
        return null;
    }

    public static File getJpegFileNameForRawFile(File rawFile) {
        if (isSupportedRawFile(rawFile)) {
            File file = new File(rawFile.getParent(), rawFile.getName().replace(
                    ".CR2", ".jpg"));
            return file;
        } else
            return rawFile;
    }

    public void convertRawFiles(File rawFile, File destFolder) {
        String homeFolder = System.getProperty("user.home");
        File tmpFolder = new File(homeFolder + "/tmp");
        File tempFile = new File(tmpFolder, rawFile.getName());
        try {
            FileUtils.copyFile(rawFile, tempFile);
            Process p = Runtime.getRuntime().exec(
                    DCRAW_PATH + " -e " + tempFile);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(
                    p.getErrorStream()));

            String s = null;
            // read the output from the command
            while ((s = stdInput.readLine()) != null) {
                LOGGER.debug(s);
            }

            // read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
                LOGGER.debug(s);
            }
            File tempJpegFile = new File(tmpFolder,
                    getFilenameForThumbnail(rawFile));
            BufferedImage read = ImageIO.read(tempJpegFile);
            File previewImage = new File(destFolder,
                    getFilenameForPreviewJPG(rawFile));
            ImageImporter.createScaledImage(previewImage, read,
                    ImageImporter.PREVIEW_WIDTH, ImageImporter.PREVIEW_HEIGHT);
            FileUtils.copyFile(tempJpegFile, new File(destFolder,
                    getFilenameForOriginalJPG(rawFile)));
            LOGGER.info("Copying original file " + rawFile.getName() + " to "
                    + destFolder.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                FileUtils.deleteDirectory(tmpFolder);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String getFilenameWithoutExtension(File file) {
        return getFilenameWithoutExtension(file.getName());
    }

    public static String getFilenameWithoutExtension(String filename) {
        int lastIndexOf = filename.lastIndexOf(".");
        return filename.substring(0, lastIndexOf);
    }

    public static String getFilenameForThumbnail(File file) {
        return getFilenameWithoutExtension(file) + ".thumb.jpg";
    }

    public static String getFilenameForPreviewJPG(File file) {
        return getFilenameWithoutExtension(file) + ".preview.jpg";
    }

    public static String getFilenameForOriginalJPG(File file) {
        return getFilenameWithoutExtension(file) + ".orig.jpg";
    }

    public static String getPathWithoutFileName(String file) {
        int lastIndexOf = file.lastIndexOf("/");
        return file.substring(0, lastIndexOf);
    }

    public static void main(String[] args) {
    }
}
